package cbs.jdtag;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import cbs.jdtag.io.XMLReader;

public class NewAlignmentDialog extends JDialog implements ActionListener {

	private static final long serialVersionUID = 392452585844371419L;
	private static final String leftActionCmd = "srcOpen";
	private static final String rightActionCmd = "tgtOpen";
	private static final String okActionCmd = "ok";

	private transient final Logger logger = Logger.getLogger(this.getClass().getName());
	
	private final JFileChooser fd = new JFileChooser();
	
	private JLabel srcFileLabel = new JLabel("Source token file");
	private JTextField srcFileTextField = new JTextField();
	private JButton srcOpenButton = new JButton("Open");
	
	private JLabel tgtFileLabel = new JLabel("Target token file");
	private JTextField tgtFileTextField = new JTextField();
	private JButton tgtOpenButton = new JButton("Open");
	
	private JButton okButton = new JButton("OK");
	
	public NewAlignmentDialog() {
		super(AppContext.mainView, "New alignment");
		
		setIconImage(AppContext.getIcon());
		setModal(true);
		
		fd.setMultiSelectionEnabled(false);
		fd.setFileSelectionMode(JFileChooser.FILES_ONLY);
		
		srcFileTextField.setEditable(false);
		tgtFileTextField.setEditable(false);
		srcOpenButton.setActionCommand(leftActionCmd);
		srcOpenButton.addActionListener(this);
		tgtOpenButton.setActionCommand(rightActionCmd);
		tgtOpenButton.addActionListener(this);
		okButton.setActionCommand(okActionCmd);
		okButton.addActionListener(this);
		
		setLayout(new GridBagLayout());
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.fill = GridBagConstraints.BOTH;
		
		// labels
		gbc.weightx = 0.0;
		gbc.weighty = 0.5;
		
		gbc.gridx = 0;
		gbc.gridy = 0;
		add(srcFileLabel, gbc);
		
		gbc.gridx = 0;
		gbc.gridy = 1;
		add(tgtFileLabel, gbc);
		
		// textfields
		gbc.gridwidth = 3;
		gbc.weightx = 1.0;
		gbc.weighty = 0.5;
		
		gbc.gridx = 1;
		gbc.gridy = 0;
		add(srcFileTextField, gbc);

		gbc.gridx = 1;
		gbc.gridy = 1;
		add(tgtFileTextField, gbc);
		
		// buttons
		gbc.gridwidth = 1;
		gbc.weightx = 0.0;
		gbc.weighty = 0.5;
		
		gbc.gridx = 4;
		gbc.gridy = 0;
		add(srcOpenButton, gbc);

		gbc.gridx = 4;
		gbc.gridy = 1;
		add(tgtOpenButton, gbc);
		
		// ok button
		gbc.gridx = 0;
		gbc.gridy = 2;
		gbc.gridwidth = 5;
		gbc.weightx = 1.0;
		gbc.weighty = 0.5;
		add(okButton, gbc);
		
		setSize(500, 110);
		setResizable(false);
		setLocationRelativeTo(AppContext.mainView);
	}
	
	public void actionPerformed(ActionEvent ae) {
		
		if (ae.getActionCommand().equals(leftActionCmd) || ae.getActionCommand().equals(rightActionCmd)) {
			fd.setCurrentDirectory(new File(AppContext.getRecentlyUsedDir()));
			int retVal = fd.showDialog(AppContext.mainView, "Add token file");
		
			if (retVal == JFileChooser.APPROVE_OPTION) {
				AppContext.setRecentlyUsedDir(fd.getCurrentDirectory().getPath());
				
				if (ae.getActionCommand().equals(leftActionCmd)) {
					srcFileTextField.setText(fd.getSelectedFile().toString());
				}
				else if (ae.getActionCommand().equals(rightActionCmd)) {
					tgtFileTextField.setText(fd.getSelectedFile().toString());
				}
			}
		}
		else if (ae.getActionCommand().equals(okActionCmd)) {
			DataModel2 dm = AppContext.getDM();
			
			setVisible(false);
			
			dm.reset();
			AppContext.mainView.setTitle("jdtag");
			AppContext.mainView.setCmdInputFieldEnabled(false);

			try {					
				// parse src token file
				String srcKey = "a";
				dm.addKey(srcKey);
				URI srcUri = new File(srcFileTextField.getText()).toURI();
				XMLReader.parseTokenFile(srcUri, srcKey, "");
				
				String tgtKey = "b";
				dm.addKey(tgtKey);
				URI tgtUri = new File(tgtFileTextField.getText()).toURI();
				XMLReader.parseTokenFile(tgtUri, tgtKey, "");
				
				String sf = getFilepathWithoutExtension(srcUri);
				String tf = getFilepathWithoutExtension(tgtUri);
				if (sf.equals(tf)) {
					dm.setAlignmentFile(new File(sf + ".atag"));
				}
				else {
					dm.setAlignmentFile(new File(AppContext.getRecentlyUsedDir() + "/newAlignment.atag"));
				}
				
				AppContext.mainView.setTitle("jdtag: " + dm.getAlignmentFile());
				AppContext.mainView.setCmdInputFieldEnabled(true);
				AppContext.mainView.setStatusText("Files loaded.");
			}
			catch (Exception e) {
				logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
				JOptionPane.showMessageDialog(AppContext.mainView,
						e.getLocalizedMessage(), "Parse error",
						JOptionPane.ERROR_MESSAGE);
				AppContext.mainView.setStatusText("Parse error.");
				return;
			}
		}
	}
	
	private String getFilepathWithoutExtension(URI uri) {
		File f = new File(uri);
		int pos;
		String ext = f.getName();
		
		pos = ext.lastIndexOf('.');
		if (pos > -1) {
			ext = ext.substring(0, pos);
		}
		
		return ext;
	}
}